<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--组织数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="orgName" placeholder="请输入组织名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree ref="orgTree" :data="options.orgOptions" :expand-on-click-node="false" :filter-node-method="filterNode" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>

      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <!-- 高级查询 -->
        <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" size="small" style="width: 240px" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" size="small" style="width: 240px" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" size="small" style="width: 240px" placeholder="用户状态" clearable>
              <el-option v-for="option in options.statusOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
            </el-select>
          </el-form-item>
         <el-form-item label="创建时间">
            <el-date-picker v-model="createTimeRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermission="['system:user:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermission="['system:user:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermission="['system:user:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermission="['system:user:import']" type="info" icon="el-icon-upload2" size="mini" @click="openUploadDialog">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermission="['activiti:identity:update']" type="warning" icon="el-icon-download" size="mini" @click="handleSyncIdentity">同步到工作流</el-button>
          </el-col>
          <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
        </el-row>

        <!-- 数据列表 -->
        <el-table v-loading="loading" :data="page.records" highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户名称" align="center" prop="userName" show-overflow-tooltip />
          <el-table-column label="用户昵称" align="center" prop="nickName" show-overflow-tooltip />
          <!--<el-table-column label="组织" align="center" prop="orgName" show-overflow-tooltip />-->
          <el-table-column label="手机号码" align="center" prop="phone" />
          <!--<el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
            </template>
          </el-table-column>-->
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-hasPermission="['system:user:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
              <!--<el-button v-hasPermission="['system:user:resetPassword']" size="mini" type="text" icon="el-icon-key" @click="handleResetPassword(scope.row)">重置密码</el-button>-->
              <el-button v-if="scope.row.id !== 1" v-hasPermission="['system:user:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="userFormDialog.title" :visible.sync="userFormDialog.visible" :close-on-click-modal="false" width="500px" append-to-body>
          <el-form ref="userForm" :model="userFormData" :rules="userFormRules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户类型" prop="userType">

              <el-select v-model="userFormData.userType" style="width: 100%" filterable clearable placeholder="请选择用户类型" >
                <el-option v-for="option in options.userTypeOptions" :key="option.key" :label="option.lable" :value="option.key" />
              </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="userFormData.userType === `供应商`">

                <el-select v-model="userFormData.supplierId" style="width: 100%" filterable clearable placeholder="请选择供应商" @change="handleSelected">
                  <el-option v-for="option in options.supplierIdOptions" :key="option.id" :label="option.supplierName" :value="option.id" />
                </el-select>
              </el-col>
                <el-col :span="12" v-if="userFormData.userType === `保理公司`">

                <el-select v-model="userFormData.baoliCompanyId" style="width: 100%" filterable clearable placeholder="请选择保理公司" @change="handleSelected">
                  <el-option v-for="option in options.baoliOptions" :key="option.id" :label="option.companyName" :value="option.id" />
                </el-select>
              </el-col>
              <el-col :span="12" v-if="userFormData.userType === `贸易商`">

                <el-select v-model="userFormData.customerId" style="width: 100%" filterable clearable placeholder="请选择贸易商" @change="handleSelected">
                  <el-option v-for="option in options.customers" :key="option.id" :label="option.customerName" :value="option.id" />
                </el-select>
              </el-col>
              <el-col :span="12" v-if="userFormData.userType === `买家客户`">

                <el-select v-model="userFormData.storeId" style="width: 100%" filterable clearable placeholder="请选择买家客户" @change="handleSelected">
                  <el-option v-for="option in options.storeOptions" :key="option.id" :label="option.storeName" :value="option.id" />
                </el-select>
              </el-col>
               <el-col :span="12" v-if="userFormData.userType === `平台公司`">

               <el-form-item label="归属组织" prop="orgId">
                 <treeselect v-model="userFormData.orgId" :options="options.orgOptions" :show-count="true" :normalizer="normalizer" placeholder="请选择归属组织" />
               </el-form-item>

              <el-form-item label="工种" prop="userJob">

              <el-select v-model="userFormData.userJob" style="width: 100%" filterable clearable placeholder="请选择用户类型" >
                <el-option v-for="option in options.userTypes" :key="option.key" :label="option.lable" :value="option.key" />
              </el-select>
                </el-form-item>
                 </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input v-model="userFormData.nickName" placeholder="请输入用户昵称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
               <el-form-item label="身份证号">
                  <el-input v-model="userFormData.idCardNo" placeholder="请输入身份证号" maxlength="19" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="userFormData.phone" placeholder="请输入手机号码" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span="12" >
                <el-form-item label="角色">
                  <el-select v-model="userFormData.roleIds" multiple placeholder="请选择">
                    <el-option v-for="option in options.roleOptions" :key="option.id" :label="option.roleName" :value="option.id" :disabled="option.status == '1'" />
                  </el-select>
                </el-form-item>
              </el-col>
              <!--<el-col :span="12">
                <el-form-item label="邮箱">
                  <el-input v-model="userFormData.email" placeholder="请输入邮箱" maxlength="50" />
                </el-form-item>
              </el-col>-->
            </el-row>
            <!--<el-row>
              <el-col :span="12">
                <el-form-item v-if="!userFormData.id" label="用户名称" prop="userName">
                  <el-input v-model="userFormData.userName" placeholder="请输入用户名称" />
                </el-form-item>
              </el-col>
              &lt;!&ndash;<el-col :span="12">
                <el-form-item v-if="!userFormData.id" label="用户密码" prop="password">
                  <el-input v-model="userFormData.password" placeholder="请输入用户密码" type="password" />
                </el-form-item>
              </el-col>&ndash;&gt;
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户性别">
                  <el-select v-model="userFormData.sex" placeholder="请选择">
                    <el-option v-for="option in options.sexOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-radio-group v-model="userFormData.status">
                    <el-radio v-for="option in options.statusOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="岗位">
                  <el-select v-model="userFormData.postIds" multiple placeholder="请选择">
                    <el-option v-for="option in options.postOptions" :key="option.id" :label="option.postName" :value="option.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色">
                  <el-select v-model="userFormData.roleIds" multiple placeholder="请选择">
                    <el-option v-for="option in options.roleOptions" :key="option.id" :label="option.roleName" :value="option.id" :disabled="option.status == '1'" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>-->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="userFormData.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="confirmUserFormDialog">确 定</el-button>
            <el-button @click="resetUserFormDialog">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="uploadDialog.title" :visible.sync="uploadDialog.visible" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            :headers="uploadData.headers"
            :action="uploadData.url + '?updateSupport=' + uploadData.updateSupport"
            :disabled="uploadData.isUploading"
            :on-progress="handleUploadProgress"
            :on-success="handleUploadSuccess"
            :auto-upload="false"
            accept=".xlsx, .xls"
            drag
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              <el-checkbox v-model="uploadData.updateSupport" />是否更新已经存在的数据
              <el-link type="info" style="font-size:12px" @click="handleDownloadTemplate">下载模板</el-link>
            </div>
            <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="confirmUploadDialog">确 定</el-button>
            <el-button @click="resetUploadDialog">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import UserApi from '@/api/system/UserApi'
import AuthUtils from '@/utils/AuthUtils'
import OrgApi from '@/api/system/OrgApi'
import RoleApi from '@/api/system/RoleApi'
import PostApi from '@/api/system/PostApi'
import DictValueApi from '@/api/system/DictValueApi'
import ConfigApi from '@/api/system/ConfigApi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import appConstant from '@/constant/AppConstant'
import CustomerApi from '@/api/basic/CustomerApi'
import BaoliCompanyApi from '@/api/baoliCompany/BaoliCompanyApi'
import StoreApi from '@/api/basic/StoreApi'
import SupplierApi from '@/api/basic/SupplierApi'
const defaultUserFormData = {
  id: null,
  orgId: null,
  userName: null,
  nickName: null,
   customerId: null,
    supplierId: null,
     storeId: null,
     baoliCompanyId: null,
  password: null,
  phone: null,
  email: null,
  sex: null,
  status: '0',
  remark: null,
  userJob: null,
  postIds: [],
  roleIds: ['2']
}
export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      options: {
        statusOptions: [], // 状态数据字典
        sexOptions: [], // 性别状态字典
        orgOptions: [], // 组织树选项
        postOptions: [], // 岗位选项
        userTypeOptions: appConstant.userTypeList,
        userTypes: appConstant.userType,
         supplierIdOptions: [],
         baoliOptions: [],
         storeOptions: [],
         customers: [],
        roleOptions: [] // 角色选项
      },
      queryParams: {
        userName: null,
        phone: null,
        status: null,
        orgId: null
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      userFormDialog: {
        title: '',
        visible: false
      },
      userFormData: Object.assign({}, defaultUserFormData),
      userFormRules: {
        userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
        orgId: [{ required: true, message: '归属组织不能为空', trigger: 'change' }],
        password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
        userType: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      uploadDialog: {
        title: '用户导入',
        visible: false
      },
      uploadData: {
        headers: { Authorization: 'Bearer ' + AuthUtils.getToken() }, // 上传请求头
        url: process.env.VUE_APP_BASE_API + '/system/user/importData', // 上传的地址
        isUploading: false, // 是否禁用上传
        updateSupport: 0 // 是否更新已经存在的数据
      },
      orgName: null, // 组织名称
      initPassword: null, // 默认密码
      createTimeRange: [], // 日期范围
      loading: true,
      isSingle: true,
      isMultiple: true,
      searchVisible: true,
      multipleSelection: []
    }
  },
  watch: {
    // 根据名称筛选组织树
    orgName(val) {
      this.$refs.orgTree.filter(val)
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_yn_type' }).then(response => {
        this.options.isSystemicOptions = response.data
      })
      OrgApi.treeSelect().then(response => {
        this.options.orgOptions = response.data
      })
      RoleApi.options().then(response => {
        this.options.roleOptions = response.data
      })
      PostApi.list().then(response => {
        this.options.postOptions = response.data
      })
      CustomerApi.list().then(response => {
        this.options.customers = response.data
      })
      StoreApi.list().then(response => {
        this.options.storeOptions = response.data
      })
      SupplierApi.list().then(response => {
           this.options.supplierIdOptions = response.data
         })
      BaoliCompanyApi.list().then(response => {
           this.options.baoliOptions = response.data
         })

      DictValueApi.list({ dictCode: 'sys_enable_disable' }).then(response => {
        this.options.statusOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_sex_type' }).then(response => {
        this.options.sexOptions = response.data
      })
      ConfigApi.list('sys.user.initPassword').then(response => {
        this.initPassword = response.msg
      })
    },
    handleAdd() {
      this.openUserFormDialog()
    },

    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return UserApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openUserFormDialog(id)
    },
    handleQuery() {
      this.loading = true
      //UserApi.page(this.$common.addDateRange(this.queryParams, this.createTimeRange), this.page).then(response => {
       UserApi.page(this.queryParams, this.page).then(response => {

        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return UserApi.exportUser(queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    handleSyncIdentity() {
      const that = this
      this.$confirm('是否确认同步所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return UserApi.syncIdentity()
      }).then(function() {
        that.$message.success('同步成功')
      })
    },
    openUserFormDialog(id) {
      this.resetUserFormDialog()
      this.userFormDialog.visible = true
      if (id) {
        this.userFormDialog.title = '用户-修改'
        UserApi.get(id).then(response => {
          this.userFormData = response.data
          this.userFormData.password = null
          if (this.userFormData.userRoles) {
            this.userFormData.roleIds = this.userFormData.userRoles.map(role => role.id)
          }
          if (this.userFormData.userPosts) {
            this.userFormData.postIds = this.userFormData.userPosts.map(post => post.id)
          }
        })
      } else {
        this.userFormDialog.title = '用户-添加'
        this.userFormData.password = this.initPassword
      }
    },
    confirmUserFormDialog() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          if (this.userFormData.id) {
            UserApi.updateRolePost(this.userFormData).then(response => {
              this.$message.success('修改成功')
              this.userFormDialog.visible = false
              this.handleQuery()
            })
          } else {
            UserApi.add(this.userFormData).then(response => {
              this.$message.success('添加成功')
              this.userFormDialog.visible = false
              this.handleQuery()
            })
          }
        }
      })
    },
    resetUserFormDialog() {
      this.userFormDialog = {
        title: '',
        visible: false
      }
      this.userFormData = Object.assign({}, defaultUserFormData)
      this.resetForm('userForm')
    },
    openUploadDialog() {
      this.resetUploadDialog()
      this.uploadDialog.visible = true
    },
    confirmUploadDialog() {
      this.$refs.upload.submit()
    },
    resetUploadDialog() {
      this.uploadDialog.visible = false
    },
    handleDownloadTemplate() {
      UserApi.importTemplate().then(response => {
        this.$common.download(response.data)
      })
    },
    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {
      this.uploadData.isUploading = true
    },
    // 文件上传成功处理
    handleUploadSuccess(response, file, fileList) {
      this.uploadDialog.visible = false
      this.uploadData.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data ? response.data : response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id
      this.handleQuery()
    },
    handleStatusChange(row) {
      const display = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + display + '"用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return UserApi.edit({ id: row.id, status: row.status })
      }).then(() => {
        this.$message.success(display + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    handleResetPassword(row) {
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        UserApi.resetPassword(row.id, value).then(response => {
          this.$message.success('修改成功，新密码是：' + value)
        })
      }).catch(() => {})
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return node
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.page.current = 1
      this.createTimeRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
